package com.swang.pms.web.controller.manage;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.swang.pms.common.util.EnumToDataUtil;
import com.swang.pms.common.util.LoggerUtil;
import com.swang.pms.model.annotation.PltLog;
import com.swang.pms.model.common.Pager;
import com.swang.pms.model.dto.ManageRoleDto;
import com.swang.pms.model.entity.CurrentKey;
import com.swang.pms.model.entity.ManageRole;
import com.swang.pms.model.entity.ManageUser;
import com.swang.pms.model.enums.Status;
import com.swang.pms.model.vo.ResultMessage;
import com.swang.pms.service.manage.ManageRoleService;
import com.swang.pms.web.controller.BaseController;

/**
 * @ClassName: ManageRoleController
 * @Description: 角色服务控制层
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
@Controller
@RequestMapping("/manageRole")
public class ManageRoleController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ManageRoleController.class);

    @Resource
    ManageRoleService           manageRoleService;

    @RequestMapping(value = "/page")
    public String page(ModelMap model) {
        String statusComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(Status.class);
        model.put("statusComboData", statusComboData);
        return "sys/pageManageRole";
    }

    @RequestMapping(value = "/editRole")
    public String editRole(ModelMap model, @RequestParam("type") String type) {
        String statusComboData = EnumToDataUtil.getDHEnumsValuesFromEnum(Status.class);
        model.put("statusComboData", statusComboData);
        model.put("type", type);
        return "sys/win/editManageRole";
    }

    @PltLog(log = "分页查询角色列表")
    @RequestMapping(value = "/findPageData")
    public @ResponseBody Pager findPageData(@ModelAttribute Pager page, @ModelAttribute ManageRoleDto dto) {
        Pager resultPage = new Pager();
        try {
            if (dto != null && StringUtils.isNotBlank(dto.getRoleName())) {
                dto.setRoleName(dto.getRoleName().replaceAll("%", "\\\\%"));
            }
            resultPage = this.manageRoleService.findPageDataByDto(page, dto);
        } catch (Exception e) {
            resultPage.change(false, "查询失败: " + e.getMessage());
        }
        return resultPage;
    }

    @PltLog(log = "查询角色菜单")
    @RequestMapping(value = "/showMenus/{roleId}")
    public @ResponseBody ResultMessage getMenuIdsByRoleId(@PathVariable("roleId") Long roleId, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(roleId);
        if (!checkParam(request, currentKey)) {
            result.change(false, "水平访问受限，请刷新当前页面再试!");
            return result;
        }
        try {
            List<Long> menus = this.manageRoleService.getMenuIdsByRoleId(roleId);
            result.setContent(menus);
        } catch (Exception e) {
            result.change(false, "获取失败,错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "manageRole-showMenus error: {0}", e.getMessage());
        }
        return result;
    }

    @PltLog(log = "保存角色")
    @RequestMapping(value = "/save")
    public @ResponseBody ResultMessage save(ManageRole role, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        ManageUser admin = getSessionUser(request);
        if (role.getSortNum() == null) {
            role.setSortNum(999);
        }
        try {
            int count = this.manageRoleService.countRole(role);
            if (count > 0) {
                result.change(false, "角色名已存在!");
                return result;
            }
            if (role.getId() == null) {
                CurrentKey currentKey = new CurrentKey();
                currentKey.setId(role.getRandomNum());
                if (!checkParam(request, currentKey)) {
                    result.change(false, "水平访问受限，请刷新当前页面再试!");
                    return result;
                }
                role.setGmtCreate(new Date());
                role.setGmtModify(new Date());
                role.setOperator(admin.getUserName());
                if (StringUtils.isBlank(role.getStatus())) {
                    role.setStatus(Status.ENABLED.getCode());
                }
                this.manageRoleService.addManageRole(role);
            } else {
                CurrentKey currentKey = new CurrentKey();
                currentKey.setId(role.getId());
                if (!checkParam(request, currentKey)) {
                    result.change(false, "水平访问受限，请刷新当前页面再试!");
                    return result;
                }
                this.manageRoleService.updateManageRoleByKeySelective(role);
            }
        } catch (Exception e) {
            result.change(false, "保存失败 , 错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "manageRole-save error: {0}", e.getMessage());
        }
        return result;
    }

    @PltLog(log = "保存角色菜单")
    @RequestMapping(value = "/saveMenus/{roleId}")
    public @ResponseBody ResultMessage saveMenus(@PathVariable("roleId") Long roleId, @RequestParam(value = "menus[]") Long[] menus,
                                                 HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(roleId);
        if (!checkParam(request, currentKey)) {
            result.change(false, "水平访问受限，请刷新当前页面再试!");
            return result;
        }
        try {
            this.manageRoleService.saveMenus(roleId, menus);
        } catch (Exception e) {
            result.change(false, "保存失败,错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "manageRole-saveMenus error: {0}", e.getMessage());
        }
        return result;
    }

    @PltLog(log = "更改角色状态")
    @RequestMapping(value = "/changeState")
    public @ResponseBody ResultMessage changeState(ManageRole role, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "成功");
        if (role.getId() == null) {
            result.change(false, "参数中角色id为空");
            return result;
        }
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(role.getId());
        if (!checkParam(request, currentKey)) {
            result.change(false, "水平访问受限，请刷新当前页面再试!");
            return result;
        }
        if (StringUtils.isBlank(role.getStatus())) {
            role.setStatus(Status.ENABLED.getCode());
        }
        role.setGmtModify(new Date());
        try {
            this.manageRoleService.updateManageRoleByKeySelective(role);
        } catch (Exception e) {
            result.change(false, "操作失败,错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "manageRole-changeState error: {0}", e.getMessage());
        }
        return result;
    }

    @PltLog(log = "删除角色")
    @RequestMapping(value = "/deleteRole")
    public @ResponseBody ResultMessage deleteRole(ManageRole role, HttpServletRequest request) {
        ResultMessage result = new ResultMessage(true, "删除成功");
        if (role.getId() == null) {
            result.change(false, "参数中角色id为空");
            return result;
        }
        CurrentKey currentKey = new CurrentKey();
        currentKey.setId(role.getId());
        if (!checkParam(request, currentKey)) {
            result.change (false, "水平访问受限，请刷新当前页面再试!");
            return result;
        }
        role.setStatus(Status.DELETE.getCode());
        role.setGmtModify(new Date());
        try {
            this.manageRoleService.updateManageRoleByKeySelective(role);
        } catch (Exception e) {
            result.change(false, "删除失败,错误信息:" + e.getMessage());
            LoggerUtil.error(LOGGER, "manageRole-changeState error: {0}", e.getMessage());
        }
        return result;
    }

}
